<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
  <div class="execution">
    <basic-container>
      <el-row :gutter="10">
        <el-col :span="this.clickObj ? 12 : 24">
          <avue-crud ref="crud"
                     :page="page"
                     :data="tableData"
                     :permission="permissionList"
                     :table-loading="tableLoading"
                     :option="tableOption"
                     :before-open="beforeOpen"
                     v-model="form"
                     @on-load="getPage"
                     @refresh-change="refreshChange"
                     @row-update="handleUpdate"
                     @row-save="handleSave"
                     @row-del="handleDel"
                     @sort-change="sortChange"
                     @search-change="searchChange">
            <template slot-scope="scope"
                      slot="menu">
              <el-button type="text"
                         icon="el-icon-s-claim"
                         size="mini"
                         plain
                         @click="handleItem(scope.row,scope.index)">查看备注
              </el-button>
              <el-button type="text"
                         icon="el-icon-s-claim"
                         size="mini"
                         plain
                         :style="{ display: visibleEdit }"
                         @click="editUser(scope.row,scope.index)">修改所属用户
              </el-button>
              <el-button type="text"
                         icon="el-icon-s-claim"
                         size="mini"
                         plain
                         :style="{ display: visibleEdit }"
                         @click="changeMember(scope.row,scope.index)">转会员
              </el-button>
            </template>
          </avue-crud>
        </el-col>
        <el-dialog  :visible.sync="dialogVisible" width="40%">
          <avue-form ref="form"
                     v-model="form3"
                     :option="option3"
                     @submit="subUser">
          </avue-form>
        </el-dialog>
        <el-dialog  :visible.sync="dialogVisible1" width="40%">
          <avue-form ref="form"
                     v-model="form4"
                     :option="option4"
                     @submit="subUser1">
          </avue-form>
        </el-dialog>
        <el-col :span="12" v-if="this.clickObj">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <h3><i class="el-icon-document-copy"></i> 备注列表，所属客户：{{this.clickObj.name}}</h3>
              <el-button style="float: right; padding: 3px 0" type="text" @click="handleItem()">关闭</el-button>
            </div>
            <avue-crud ref="crud2"
                       v-model="form2"
                       :page="page2"
                       :data="tableData2"
                       :permission="permissionList"
                       :before-open="beforeOpen2"
                       :option="tableOption2"
                       :table-loading="tableLoading2"
                       @on-load="getPage2"
                       @row-update="handleUpdate2"
                       @row-save="handleSave2"
                       @row-del="handleDel2"
                       @refresh-change="refreshChange2"
                       @sort-change="sortChange2">
            </avue-crud>
          </el-card>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
    import {getPage, getObj, addObj, putObj, delObj} from '@/api/upms/syscustomer'
    import {tableOption} from '@/const/crud/upms/syscustomer'
    import {mapState,mapGetters} from 'vuex'
    import { getPage as getPage2, addObj as addObj2, putObj as putObj2, delObj as delObj2 } from '@/api/upms/syscustomerre'
    import { tableOption as tableOption2 } from '@/const/crud/upms/syscustomerre'
    import {dateFormat} from "@/util/date";
    import { getObj as getObj3,getPage as getPage3} from '@/api/upms/user'
    import {addObj  as addObj4} from '@/api/mall/usercard'



    export default {
        name: 'syscustomer',
        data() {
            return {
              visibleEdit:'none',
                form: {},
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条
                    ascs: [],//升序字段
                    descs: []//降序字段
                },
                paramsSearch: {},
                tableLoading: false,
                tableOption: tableOption,
              clickObj: null,
              form2: {},
              tableData2: [],
              page2: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10, // 每页显示多少条
                ascs: [],//升序字段
                descs: 'date'//降序字段
              },
              tableLoading2: false,
              tableOption2: tableOption2,
              paramsSearch2:{},
              dialogVisible: false,
              form3: {},
              page3: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 99999, // 每页显示多少条
                ascs: [],//升序字段
                descs: []//降序字段
              },
              option3: {
                column: [
                  {
                    label: "所属用户",
                    prop: "userId",
                    rules: [{
                      required: true,
                      message: '不能为空'
                    }],
                  type: 'select',
                  dicData: []
                  }]
              },
              userId:'',
              dialogVisible1: false,
              userData:null,
              form4: {},
              option4: {
                column: [
                  {
                    label: "身份证号",
                    prop: "idCard",
                    rules: [{
                      required: true,
                      message: '不能为空'
                    }],
                  },
                  {
                    label: '商品类目',
                    prop: 'cardType',
                    type: 'cascader',
                    props: {
                      label: 'name',
                      value: 'id'
                    },
                    dicUrl: '/mall/goodscategory/tree',
                    rules: [{
                      required: true,
                      message: '请选择类目',
                      trigger: 'blur'
                    }]
                  },
                  {
                    label: '商品规格',
                    prop: 'specifications',
                    type: 'cascader',
                    props: {
                      label: 'name',
                      value: 'name'
                    },
                    rules: [{
                      required: true,
                      message: '请选择规格',
                      trigger: 'blur'
                    }],
                    dicUrl: '/mall/goodsspecvalue/tree',
                  },
                  {
                    label: '商品名',
                    prop: 'goodsName',
                    type: 'cascader',
                    props: {
                      label: 'name',
                      value: 'name'
                    },
                    rules: [{
                      required: true,
                      message: '请选择商品名',
                      trigger: 'blur'
                    }],
                    dicUrl: '/mall/goodsspu/list',
                  },
                  {
                    label: '激活时间',
                    prop: 'activationTime',
                    type: 'date',
                    valueFormat: 'yyyy-MM-dd HH:mm:ss'
                  },
                  {
                    label: '过期时间',
                    prop: 'overTime',
                    type: 'date',
                    valueFormat: 'yyyy-MM-dd HH:mm:ss'
                  },
                  {
                    label: '次数',
                    type: 'number',
                    prop: 'activation'
                  },
                  {
                    label: "入会费",
                    prop: "price",
                    type: 'number',
                    rules: [{
                      required: true,
                      message: '不能为空'
                    }],
                  },
                  {
                    label: "付款渠道",
                    prop: "priceChannel",
                    rules: [{
                      required: true,
                      message: '不能为空'
                    }],
                    type: 'select',
                    dicData: [{
                      label: '现金',
                      value: '0'
                    }, {
                      label: '刷卡',
                      value: '1'
                    }, {
                      label: '商城',
                      value: '2'
                    }, {
                      label: '其他',
                      value: '3'
                    }]
                  }
                  ]
              },
            }
        },
        created() {
          this.getObj3()
          },
        mounted: function () {
        },
        computed: {
          ...mapState({
            userInfo: state => state.user.userInfo
          }),
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.permissions['upms:syscustomer:add'] ? true : false,
                    delBtn: this.permissions['upms:syscustomer:del'] ? true : false,
                    editBtn: this.permissions['upms:syscustomer:edit'] ? true : false,
                    viewBtn: this.permissions['upms:syscustomer:get'] ? true : false
                };
            }
        },
        methods: {
          changeMember: function (row) {
            this.userData = row
            this.dialogVisible1 = true
          },
          editUser: function (row) {
            this.userId = row.id
            let dicDate = []
            let that = this
              getPage3(Object.assign({
                current: that.page3.currentPage,
                size: that.page3.pageSize,
                descs: that.page3.descs,
                ascs: that.page3.ascs,
              })).then(response => {
                let userList = response.data.data.records
                for (let i = 0;i<userList.length;i++) {
                  let list = {label: '', value: ''}
                  list.label = userList[i].username
                  list.value =userList[i].id
                  dicDate.push(list)
                }
              })
            this.option3.column[0].dicData =dicDate
            this.dialogVisible = true
          },

          subUser1(form4,done){
            if(form4.activationTime != "" || form4.overTime != ""){
              if(form4.activationTime == "" || form4.overTime == ""){
                done()
                return this.$message({
                  showClose: true,
                  message: '激活或过期时间不能为空',
                })

              }

            }else{
              if(form4.activation == undefined){
                done()
                return this.$message({
                  showClose: true,
                  message: '次数和过期时间二选一',
                })

              }
            }
            if(form4.activationTime != "" && form4.activation != undefined){
              done()
              return  this.$message({
                showClose: true,
                message: '次数和过期时间二选一，不能都填',
              })

            }
            let userCard = {};
            userCard.idCard = form4.idCard
            userCard.price = form4.price
            userCard.priceChannel = form4.priceChannel
            userCard.categoryFirst = form4.cardType[0]
            userCard.categorySecond = form4.cardType[1]
            userCard.specifications = form4.specifications[1]
            userCard.goodsName = form4.$goodsName
            userCard.activationTime = form4.activationTime
            userCard.overTime = form4.overTime
            userCard.activation = form4.activation
            userCard.phone=this.userData.phone
            userCard.name=this.userData.name
            userCard.sex=this.userData.sex
            userCard.status="0"
            userCard.cardType=form4.cardType[0] + ","+ form4.cardType[1]
            addObj4(userCard).then(response => {
              done()
              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
              this.$refs.form.resetForm();
              this.dialogVisible1 = false
              this.getPage(this.page)
            }).catch(() => {
              done()
            })

            let timeOrNum;
            if(form4.activationTime != ""){
              timeOrNum = ",激活时间：" + form4.activationTime + "-"+"过期时间：" + form4.overTime + ";"
            }else{
              timeOrNum = ",次数：" + form4.activation+ ";"
            }

            let remarks = "商品类目："+form4.$cardType+",商品规格："+form4.$specifications+",商品名称："+form4.$goodsName + timeOrNum
            if(this.userData.remarks != null){
              remarks = this.userData.remarks+remarks
            }
             putObj({
               id:this.userData.id,
               remarks:remarks,
               applyCard:'1'
             })

          },
          subUser(form3,done){
            putObj({
              id:this.userId,
              userId:form3.userId,
              userName:form3.$userId
            }).then(() => {
              done()
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
                duration: 2000
              });
              this.$refs.form.resetForm();
              this.dialogVisible = false
              this.getPage(this.page)
            }).catch(() => {
              done()
            })
          },
          getObj3() {
            let userId = this.userInfo.id
            let that = this
            getObj3(userId).then(response => {
              if(response.data.data.roleList[0].roleName === "系统管理员" || response.data.data.roleList[0].roleName === "管理员"){
                that.visibleEdit = ''
              }else{
                that.visibleEdit = 'none'
              }
            }).catch(() => {

            })
          },
            searchChange(params,done) {
              if(params.playTime != undefined){
                let a = params.playTime[0]+","+params.playTime[1]
                params.playTime = a
              }
                params = this.filterForm(params)
                this.paramsSearch = params
                this.page.currentPage = 1
                this.getPage(this.page, params)
                done()
            },
            sortChange(val) {
                let prop = val.prop ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase() : ''
                if (val.order == 'ascending') {
                    this.page.descs = []
                    this.page.ascs = prop
                } else if (val.order == 'descending') {
                    this.page.ascs = []
                    this.page.descs = prop
                } else {
                    this.page.ascs = []
                    this.page.descs = []
                }
                this.getPage(this.page)
            },
          beforeOpen(done,type){
            window.openType = type
            done()
          },

          getPage(page, params) {
              this.tableLoading = true
              let userId = this.userInfo.id
              getObj3(userId).then(response => {
                if(response.data.data.roleList[0].roleName === "系统管理员" || response.data.data.roleList[0].roleName === "管理员"){
                  getPage(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    descs: this.page.descs,
                    ascs: this.page.ascs,
                  }, params, this.paramsSearch)).then(response => {
                    for(let i = 0;i< response.data.data.records.length;i++){
                      if(response.data.data.records[i].intendedProducts!=null){
                        response.data.data.records[i].intendedProducts = response.data.data.records[i].intendedProducts.split(",")
                      }
                      if(response.data.data.records[i].playTime!=null){
                        response.data.data.records[i].playTime = response.data.data.records[i].playTime.split(",")
                      }
                    }

                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.page.currentPage = page.currentPage
                    this.page.pageSize = page.pageSize
                    this.tableLoading = false
                  }).catch(() => {
                    this.tableLoading = false
                  })
                }else{
                  getPage(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    descs: this.page.descs,
                    ascs: this.page.ascs,
                  }, params, this.paramsSearch,{
                    userId: userId
                  })).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.page.currentPage = page.currentPage
                    this.page.pageSize = page.pageSize
                    this.tableLoading = false
                  }).catch(() => {
                    this.tableLoading = false
                  })
                }
              }).catch(() => {
                this.tableLoading = false
              })




            },
            /**
             * @title 数据删除
             * @param row 为当前的数据
             * @param index 为当前删除数据的行数
             *
             **/
            handleDel: function (row, index) {
                let _this = this
                this.$confirm('是否确认删除此数据', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    _this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getPage(this.page)
                }).catch(function (err) {
                })
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate: function (row, index, done, loading) {
              window.openType = "edit"
              let aa = '';
              for (let i =0;i< row.intendedProducts.length;i++) {
                let awe = row.intendedProducts[i]+ ','
                aa += awe
              }
              row.intendedProducts = aa
              if(row.playTime!=null && row.playTime!=""){
                let a = row.playTime[0]+","+row.playTime[1]
                row.playTime = a
              }else{
                row.playTime = ''
              }
                putObj(row).then(response => {
                    this.$message({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    })
                    done()
                    this.getPage(this.page)
                }).catch(() => {
                    loading()
                })
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave: function (row, done, loading) {
              let aa = '';
              for (let i =0;i< row.intendedProducts.length;i++) {
                let awe = row.intendedProducts[i]+ ','
                aa += awe
              }
              row.intendedProducts = aa
              if(row.playTime!=null && row.playTime!=""){
                let a = row.playTime[0]+","+row.playTime[1]
                row.playTime = a
              }else{
                row.playTime = ''
              }
              row.applyCard = 0
              row.delFlag = 0
              row.userId = this.userInfo.id
              row.userName = this.userInfo.username
              row.date = dateFormat(new Date())
                 addObj(row).then(response => {
                     this.$message({
                         showClose: true,
                         message: '添加成功',
                         type: 'success'
                     })
                     done()
                     this.getPage(this.page)
                 }).catch(() => {
                     loading()
                 })
            },
            /**
             * 刷新回调
             */
            refreshChange(page) {
                this.getPage(this.page)
            },

          handleItem: function (row) {
            if(row){
              this.clickObj = row
              this.page2.currentPage = 1
              this.getPage2(this.page2)
            }else{
              this.clickObj = null
            }
          },
          beforeOpen2(done) {
            this.$set(this.form2,"customerId",this.clickObj.id)
            done()
          },
          sortChange2(val){
            let prop = val.prop ? val.prop.replace(/([A-Z])/g,"_$1").toLowerCase() : ''
            if(val.order=='ascending'){
              this.page2.descs = []
              this.page2.ascs = specIdprop
            }else if(val.order=='descending'){
              this.page2.ascs = []
              this.page2.descs = prop
            }else{
              this.page2.ascs = []
              this.page2.descs = []
            }
            this.getPage2(this.page2)
          },
          getPage2(page, params) {
            this.tableLoading2 = true
            getPage2(Object.assign({
              current: page.currentPage,
              size: page.pageSize,
              descs: this.page2.descs,
              ascs: this.page2.ascs,
            }, params, this.paramsSearch2,{
              customerId: this.clickObj.id
            })).then(response => {
              this.tableData2 = response.data.data.records
              this.page2.total = response.data.data.total
              this.page2.currentPage = page.currentPage
              this.page2.pageSize = page.pageSize
              this.tableLoading2 = false
            }).catch(() => {
              this.tableLoading2=false
            })
          },
          /**
           * @title 数据删除
           * @param row 为当前的数据
           * @param index 为当前删除数据的行数
           *
           **/
          handleDel2: function(row, index) {
            var _this = this
            this.$confirm('是否确认删除此数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(function() {
              return delObj2(row.id)
            }).then(data => {
              _this.$message({
                showClose: true,
                message: '删除成功',
                type: 'success'
              })
              this.getPage2(this.page2)
            }).catch(function(err) { })
          },
          /**
           * @title 数据更新
           * @param row 为当前的数据
           * @param index 为当前更新数据的行数
           * @param done 为表单关闭函数
           *
           **/
          handleUpdate2: function(row, index, done, loading) {
            putObj2(row).then(data => {
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
              done()
              this.getPage2(this.page2)
            }).catch(() => {
              loading()
            })
          },
          /**
           * @title 数据添加
           * @param row 为当前的数据
           * @param done 为表单关闭函数
           *
           **/
          handleSave2: function(row, done, loading) {
            row.date = dateFormat(new Date())
            addObj2(row).then(data => {
              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
              done()
              this.getPage2(this.page2)
            }).catch(() => {
              loading()
            })
          },
          /**
           * 刷新回调
           */
          refreshChange2(val) {
            this.getPage2(this.page2)
          }
        }
    }
</script>

<style lang="scss" scoped>
</style>
